<template>
  <div class="clean-apply">
    <div class="header">
      <router-link to="/main/huanjing/process" class="back-btn">
        <i class="el-icon-arrow-left"></i>
        <span>返回</span>
      </router-link>
      <h2>清洁申请</h2>
    </div>

    <div class="content a4-page">
      <div ref="printArea" class="print-area">
        <div class="print-header">
          <h1>清洁申请单</h1>
          <div class="print-no">申请编号：{{ formData.applyNo }}</div>
        </div>

        <el-form :model="formData" ref="form" :rules="rules" label-width="120px" class="application-form">
          <el-form-item label="申请编号">
            <el-input v-model="formData.applyNo" disabled></el-input>
          </el-form-item>

          <el-form-item label="申请人" prop="applicant">
            <el-input v-model="formData.applicant"></el-input>
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="formData.phone"></el-input>
          </el-form-item>

          <el-form-item label="清洁区域" prop="location">
            <el-cascader
              v-model="formData.location"
              :options="locationOptions"
              :props="{ expandTrigger: 'hover' }"
              placeholder="请选择清洁区域">
            </el-cascader>
          </el-form-item>

          <el-form-item label="清洁类型" prop="cleanType">
            <el-select v-model="formData.cleanType" placeholder="请选择清洁类型">
              <el-option label="日常保洁" value="日常保洁"></el-option>
              <el-option label="深度清洁" value="深度清洁"></el-option>
              <el-option label="玻璃清洗" value="玻璃清洗"></el-option>
              <el-option label="地毯清洗" value="地毯清洗"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="期望清洁时间" prop="expectedTime">
            <el-date-picker
              v-model="formData.expectedTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="清洁要求" prop="requirements">
            <el-input 
              type="textarea" 
              v-model="formData.requirements" 
              rows="4"
              placeholder="请详细描述清洁要求">
            </el-input>
          </el-form-item>

          <el-form-item label="备注">
            <el-input type="textarea" v-model="formData.remarks" rows="3"></el-input>
          </el-form-item>

        <div class="print-footer">
          <div class="signature-area">
            <div class="signature-item">
              <span>申请人：</span>
              <div class="signature-line"></div>
            </div>
            <div class="signature-item">
              <span>审批人：</span>
              <div class="signature-line"></div>
            </div>
            <div class="signature-item">
              <span>日期：</span>
              <div class="signature-line"></div>
            </div>
          </div>
        </div>

          <br><br>
          <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="submitting">提交申请</el-button>
            <el-button type="primary" icon="el-icon-printer" @click="handlePrint">打印申请</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CleanApply',
  data() {
    return {
      submitting: false,
      formData: {
        applyNo: this.generateApplyNo(),
        applicant: '',
        phone: '',
        location: [],
        cleanType: '',
        expectedTime: [],
        requirements: '',
        remarks: ''
      },
      locationOptions: [
        {
          value: 'A区',
          label: 'A区',
          children: [
            {
              value: '1层',
              label: '1层',
              children: [
                { value: '大厅', label: '大厅' },
                { value: '走廊', label: '走廊' },
                { value: '会议室', label: '会议室' }
              ]
            }
          ]
        }
      ],
      rules: {
        applicant: [
          { required: true, message: '请输入申请人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        location: [
          { required: true, message: '请选择清洁区域', trigger: 'change' }
        ],
        cleanType: [
          { required: true, message: '请选择清洁类型', trigger: 'change' }
        ],
        expectedTime: [
          { required: true, message: '请选择期望清洁时间', trigger: 'change' }
        ],
        requirements: [
          { required: true, message: '请输入清洁要求', trigger: 'blur' },
          { min: 10, message: '清洁要求不能少于10个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    generateApplyNo() {
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const random = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
      return `QJ${year}${month}${day}${random}`
    },
    async submitForm() {
      try {
        await this.$refs.form.validate()
        this.submitting = true

        // 打印提交前的数据，用于调试
        console.log('提交的表单数据:', this.formData)

        const [startTime, endTime] = this.formData.expectedTime || []
        const [area, floor, room] = this.formData.location || []

        // 构造提交数据
        const submitData = {
          applicant: this.formData.applicant,
          phone: this.formData.phone,
          area: area,
          section: floor,
          spot: room,
          serviceType: this.formData.cleanType,
          expectedStartTime: startTime ? startTime.toISOString() : null,
          expectedEndTime: endTime ? endTime.toISOString() : null,
          requirements: this.formData.requirements,
          remarks: this.formData.remarks
        }

        // 打印实际提交到后端的数据，用于调试
        console.log('提交到后端的数据:', submitData)

        const response = await this.$http.post('/api/environment/clean/submit', submitData)
        
        if (response.data) {
          this.$message.success('清洁申请提交成功')
          this.$router.push('/main/huanjing/process')
        }
      } catch (error) {
        console.error('提交错误:', error)
        const errorMsg = error.response?.data?.message || '提交失败，请稍后重试'
        this.$message.error(errorMsg)
      } finally {
        this.submitting = false
      }
    },
    resetForm() {
      this.$refs.form.resetFields()
      this.formData.applyNo = this.generateApplyNo()
      this.formData.location = []
      this.formData.expectedTime = []
    },
    handlePrint() {
      this.$confirm('确认打印申请单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        window.print()
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.clean-apply {
  padding: 20px;

  .header {
    margin-bottom: 30px;
    position: relative;
    text-align: center;

    .back-btn {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      text-decoration: none;
      color: #606266;
      display: flex;
      align-items: center;
    }

    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }

    .header-actions {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .content {
    background: #fff;
    padding: 0;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    &.a4-page {
      width: 210mm;  /* A4 纸宽度 */
      min-height: 297mm; /* A4 纸高度 */
      margin: 0 auto;
      padding: 20mm; /* A4 纸边距 */
      background: white;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      
      @media print {
        width: 210mm;
        height: 297mm;
        margin: 0;
        padding: 20mm;
        box-shadow: none;
        
        /* 打印时隐藏不需要的元素 */
        .header, 
        .el-button:not(.print-show) {
          display: none !important;
        }
      }

      .print-header {
        text-align: center;
        margin-bottom: 30px;
        
        h1 {
          font-size: 24px;
          margin: 0 0 15px;
          font-weight: bold;
        }
        
        .print-no {
          font-size: 14px;
          color: #606266;
        }
      }

      .print-footer {
        margin-top: 50px;
        
        .signature-area {
          display: flex;
          justify-content: space-between;
          padding: 0 50px;
          
          .signature-item {
            text-align: center;
            
            span {
              display: block;
              margin-bottom: 20px;
            }
            
            .signature-line {
              width: 150px;
              height: 1px;
              background: #000;
            }
          }
        }
      }
    }
  }

  .application-form {
    width: 100%;
    margin: 0 auto;
    
    /* 调整表单元素在 A4 中的布局 */
    .el-form-item {
      margin-bottom: 15px;
    }
    
    .el-input, 
    .el-select,
    .el-date-picker {
      width: 100%;
    }
    
    .el-textarea__inner {
      min-height: 80px;
    }
  }
}

/* 打印样式 */
@media print {
  .clean-apply {
    padding: 0;
    background: white;
    
    .header {
      display: none;
    }
    
    .content {
      box-shadow: none;
      
      .el-form-item__label {
        color: #000 !important;
      }
      
      .el-input__inner,
      .el-textarea__inner {
        border: none;
        color: #000 !important;
      }
      
      .el-button {
        display: none;
      }
    }
    
    .print-header,
    .print-footer {
      display: block !important;
    }
  }
}
</style> 